#ifndef __TIMERQUEUE_H__
#define __TIMERQUEUE_H__
#include "NonCopyable.h"
#include "Timestamp.h"
#include "Channel.h"

#include <functional>
#include <iostream>
#include <vector>
#include <set>
#include <memory>
#include <atomic>

using muduo::Timestamp;
using std::vector;
using std::set;
using std::unique_ptr;


class EventLoop;
class TimerId;
class Timer;
class TimerQueue : NonCopyable
{
public:
    typedef std::function<void()> TimerCallback;
    typedef std::pair<Timestamp, Timer*> Entry;
    typedef set<Entry> TimerList;
    typedef std::pair<Timer*, int64_t> ActiveTimer;
    typedef std::set<ActiveTimer> ActiveTimerSet;

    TimerQueue(EventLoop *loop);
    ~TimerQueue();

    // 通常会跨线程调用 需要保证线程安全
    TimerId addTimer(const TimerCallback &cb, Timestamp when, double interval);
    void cancel(TimerId timerId);

    void addTimerInLoop(Timer *timer); // 修改定时器列表
    void cancelInLoop(TimerId timerId);
private:
    void handleRead();
    // 从_timers中移除到期的Timer 通过vector返回
    vector<Entry> getExpired(Timestamp now);
    void reset(const vector<Entry> &expired, Timestamp now);

    bool insert(Timer* timer);

    EventLoop *_loop;
    const int _timerfd;
    Channel _timerfdChannel;
    TimerList _timers;

    // for cancel()
    ActiveTimerSet _activeTimers;
    std::atomic_bool _callingExpiredTimers; /* atomic */
    ActiveTimerSet _cancelingTimers;
};

#endif